const path = require("path");
const addPath = (dir) => path.join(__dirname, dir);
const CracoLessPlugin = require("craco-less");
const { name } = require("./package.json");
const WebpackObfuscator = require("webpack-obfuscator");
const WebpackBar = require("webpackbar");
var sm = require("speed-measure-webpack-plugin");
const { whenProd } = require("@craco/craco");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); // 分析模块大小

const PORT = 9000;
let HOST = "127.0.0.1";
const publicPath = {
  development: `http://${HOST}:${PORT}`,
  // production: `https://xxxxx/${name}`,
  production: `.`,
};

const spm = new sm();

module.exports = {
  devServer: {
    port: PORT,
    client: {
      webSocketURL: {
        hostname: HOST,
      },
    },
  },
  webpack: spm.wrap({
    alias: {
      "@": addPath("src"),
    },
    configure: {
      output: {
        publicPath: publicPath[process.env.NODE_ENV] + "/",
        library: `${name}-[name]`,
        libraryTarget: "umd",
        chunkLoadingGlobal: `webpackJsonp_${name}`,
        // filename: "[name]-bundle.js",
        // chunkFilename: "[name]-chunk.js",
        // path: __dirname + "/dist",
      },
      module: {
        rules: [
          ...whenProd(() => {
            return [
              {
                test: /\.(js|ts)$/,
                enforce: "post",
                use: [
                  {
                    loader: WebpackObfuscator.loader,
                    options: {
                      compact: false,
                      controlFlowFlattening: true,
                      controlFlowFlatteningThreshold: 1,
                      numbersToExpressions: true,
                      simplify: true,
                      shuffleStringArray: true,
                      splitStrings: true,
                      stringArrayThreshold: 1,
                      stringArrayEncoding: ["base64"],
                    },
                  },
                ],
                include: [path.resolve(__dirname, "src/api")],
              },
            ];
          }, []),
        ],
      },
    },
    plugins: [
      // new WebpackBar(), // 显示打包进度，现在会报错，先注释
      // new BundleAnalyzerPlugin({
      //   analyzerMode: "server",
      //   analyzerHost: "127.0.0.1",
      //   analyzerPort: 8888,
      //   openAnalyzer: true, // 构建完打开浏览器
      //   reportFilename: path.resolve(__dirname, `analyzer/index.html`),
      // }),
    ],
  }),
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: {},
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
};
